Imports KOR.Helpers
Imports KOR.Support
Imports Telerik.Web.UI
Imports System.Web.HttpContext


Namespace BL

    Public Module Files

        Enum StorageModes
            [Default] = 0
            [Database] = 1
            [FileSystem] = 2
        End Enum

        Function GetFile(FileID As Integer) As IDataReader
            Dim Sql As String
            Sql = "SELECT * from FileUploads WHERE FileID = @FileID"

            Dim params As New Dictionary(Of String, Object)
            params.Add("FileID", FileID)

            Return DDA.SelectData(Sql, params)
        End Function

        Function DeleteFile(FileID As Integer) As Integer
            Dim Path As String = ""
            Using reader As IDataReader = GetFile(FileID)
                If reader.Read Then
                    If CBool(ValueOrDefault(reader("IsPath"), False)) Then Path = reader("FilePath").ToString
                End If

            End Using

            Dim delCount As Integer = DDA.Delete("FileUploads", "FileID = " & FileID.ToString.MakeSQLCompliant & " ", False)

            'If delCount > 0 And Path <> "" Then
            '    Dim rootPath As String = CombinePath(BaseStoragePath, Path)
            '    If IO.File.Exists(rootPath) Then
            '        Try
            '            IO.File.SetAttributes(rootPath, IO.FileAttributes.Normal)
            '            IO.File.Delete(rootPath)
            '        Catch ex As Exception
            '        End Try
            '    End If
            'End If

            Return delCount
        End Function

        Public Function SaveFile(file As Telerik.Web.UI.UploadedFile, section As String) As Integer
            section = MakeSectionUniform(section)

            Dim data As Byte() = New Byte(CInt(file.ContentLength - 1)) {}
            file.InputStream.Read(data, 0, CInt(file.ContentLength))
            file.InputStream.Close()

            Dim fileID As Integer = SaveFile(file.FileName, file.ContentType, data, "", section)

            Return fileID
        End Function

        Public Function SaveFile(file As Telerik.Web.UI.UploadedFile, section As String, _
                                 ReferenceTableName As String, ReferenceFieldFileID As String, _
                                 ReferenceFieldOther As String, ReferenceFieldOtherValue As Object, _
                                 AdditionalReferenceFieldValues As Dictionary(Of String, Object)) As Integer

            section = MakeSectionUniform(section)

            Dim fileID As Integer = SaveFile(file, section)

            Dim refDict As New Dictionary(Of String, Object)
            refDict.Add(ReferenceFieldFileID, fileID)
            refDict.Add(ReferenceFieldOther, ReferenceFieldOtherValue)

            If AdditionalReferenceFieldValues.Count > 0 Then
                For Each entry As KeyValuePair(Of String, Object) In AdditionalReferenceFieldValues
                    refDict.Add(entry.Key, entry.Value)
                Next
            End If

            DDA.Insert(ReferenceTableName, refDict)

            Return fileID
        End Function

        Public Function SaveFile(name As String, contentType As String, data As Byte(), description As String, section As String) As Integer
            section = MakeSectionUniform(section)

            If GetStorageModeBySection(section) = StorageModes.FileSystem Then
                Return 0 'SaveToFileSystem(name, contentType, data, description, section)
            Else
                Return SaveToDatabase(name, contentType, data, description, section)
            End If
        End Function

        Public Function SaveFile(name As String, contentType As String, path As String, description As String, section As String) As Integer
            section = MakeSectionUniform(section)

            If GetStorageModeBySection(section) = StorageModes.FileSystem Then
                Return 0 'SaveToFileSystem(name, contentType, path, description, section)
            Else
                Return SaveToDatabase(name, contentType, path, description, section)
            End If
        End Function

        Public Function GetStorageModeBySection(section As String) As StorageModes
            section = MakeSectionUniform(section)

            Dim storageMode As StorageModes
            section = section.ToLower

            Select Case section
                Case "employee/photo"
                    storageMode = StorageModes.Database
                Case Else
                    storageMode = StorageModes.Default
            End Select
            'If storageMode = StorageModes.Default Then storageMode = Settings.GetDefaultStorageMode

            Return storageMode
        End Function

        'Public Function GetSectionPath(section As String) As String
        '    section = section.Replace("\", "/") ' we want to make sure that all slashes are uniform. '/ is globally accepted directory separation

        '    Dim destFolder As String = CombinePath(BaseStoragePath, section)
        '    If Not IO.Path.IsPathRooted(destFolder) Then destFolder = HttpContext.Current.Server.MapPath(destFolder)
        '    If Not IO.Directory.Exists(destFolder) Then IO.Directory.CreateDirectory(destFolder)

        '    Return destFolder
        'End Function

        Private Function MakeSectionUniform(section As String) As String
            section = section.Replace("\", "/").ToLower ' we want to make sure that all slashes are uniform. '/ is globally accepted directory separation
            Return section
        End Function

        Public Function GetFiles(FileIds As String) As IDataReader
            Dim sql As String = "SELECT * FROM FileUploads WHERE FileID IN (" & FileIds & ")"
            Return DDA.SelectData(sql)
        End Function

        


#Region "Saving files"

        Private Function SaveToDatabase(name As String, contentType As String, data As Byte(), description As String, section As String) As Integer
            section = MakeSectionUniform(section)

            Dim fileID As Integer

            Dim dict As New Dictionary(Of String, Object)
            dict.Add("FileName", name)
            dict.Add("Section", section)
            dict.Add("FileContentType", contentType)
            dict.Add("IsPath", False)
            dict.Add("FileData", data)
            dict.Add("Description", description)
            dict.Add("UploadedDate", Now)
            dict.Add("UploadedByID", UserID)

            fileID = DDA.Insert("FileUploads", dict)

            Return fileID
        End Function

        Private Function SaveToDatabase(name As String, contentType As String, OriginalFilePath As String, description As String, section As String) As Integer
            section = MakeSectionUniform(section)

            Dim fileID As Integer

            Dim data As Byte() = New Byte() {}

            If Not IO.Path.IsPathRooted(OriginalFilePath) Then OriginalFilePath = System.Web.HttpContext.Current.Server.MapPath(OriginalFilePath)

            If IO.File.Exists(OriginalFilePath) Then
                data = IO.File.ReadAllBytes(OriginalFilePath)
            Else
                Throw New Exception("File does not exist.")
            End If


            Dim dict As New Dictionary(Of String, Object)
            dict.Add("FileName", name)
            dict.Add("Section", section)
            dict.Add("FileContentType", contentType)
            dict.Add("IsPath", False)
            dict.Add("FileData", data)
            dict.Add("Description", description)
            dict.Add("UploadedDate", Now)
            dict.Add("UploadedByID", UserID)

            fileID = DDA.Insert("FileUploads", dict)

            Return fileID
        End Function

#End Region


    End Module

End Namespace
